<?php

/**
 * JingYao-backend
 *
 * @link     https://gitee.com/wang-zhihui-release/jingyao-backend
 * @apiDocument https://gitee.com/wang-zhihui-release/jingyao-backend/wikis/
 */

namespace App\Services;

use App\Enums\AdminActionTypeEnum;
use App\Enums\CheckStatusEnum;
use App\Exceptions\ApiException;
use App\Format\InstitutionFormat;
use App\Format\LeaderProfileFormat;
use App\Format\QingfengProposalFormat;
use App\Models\Institution;
use App\Models\LeaderProfile;
use App\Models\QingfengProposal;
use App\Models\UserProfile;

class QingfengService
{
    public function leaders()
    {
        return LeaderProfile::query()
            ->orderBy('sort')
            ->get();
    }

    public function leaderAdminList(int $page, int $pageSize, array $search)
    {
        $builder = LeaderProfile::query()->orderBy('sort');

        if (isset($search['post'])) {
            $builder->where('post', $search['post']);
        }

        if (isset($search['name'])) {
            $builder->where('name', $search['name']);
        }

        $count = $builder->count();

        $list = $builder->skip(($page - 1) * $pageSize)->take($pageSize)->get();
        if (! empty($search)) {
            adminLog(new LeaderProfile(), AdminActionTypeEnum::SELECT, '查询领导列表');
        }

        return [
            'page' => $page,
            'page_size' => $pageSize,
            'count' => $count,
            'list' => $list,
        ];
    }

    public function leaderDelete(int $id)
    {
        adminLog(new LeaderProfile(), AdminActionTypeEnum::DELETE, '删除领导信息');
        LeaderProfile::query()->find($id)->delete();
        return true;
    }

    public function updateLeader(LeaderProfileFormat $leaderProfileFormat)
    {
        if (empty($leaderProfileFormat->getId())) {
            throw new ApiException('缺少参数', 1);
        }
        $leader = LeaderProfile::query()->find($leaderProfileFormat->getId());
        $data = $leaderProfileFormat->toArrayNotNull();
        unset($data['id']);
        $leader->update($data);
        adminLog($leader, AdminActionTypeEnum::UPDATE, '修改领导信息');
        return true;
    }

    public function leaderSort(int $id, int $sort)
    {
        /** @var LeaderProfile $leader */
        $leader = LeaderProfile::query()->where('id', $id)->first();
        $leader->sort = $sort;
        adminLog($leader, AdminActionTypeEnum::UPDATE, '修改领导排序');
        $leader->save();
        return true;
    }

    public function institutions()
    {
        return Institution::query()
            ->orderBy('sort')
            ->get();
    }

    public function institutionAdminList(int $page, int $pageSize, array $search)
    {
        $builder = Institution::query()->orderBy('sort');

        if (isset($search['name'])) {
            $builder->where('name', 'like', '%' . $search['name'] . '%');
        }
        $count = $builder->count();

        $list = $builder->skip(($page - 1) * $pageSize)->take($pageSize)->get();

        if (! empty($search)) {
            adminLog(new Institution(), AdminActionTypeEnum::SELECT, '查询部门列表');
        }
        return [
            'page' => $page,
            'page_size' => $pageSize,
            'count' => $count,
            'list' => $list,
        ];
    }

    public function createInstitutions(InstitutionFormat $institutionFormat)
    {
        $model = Institution::query()->create($institutionFormat->toArrayNotNull());
        adminLog($model, AdminActionTypeEnum::CREATE, '创建清风东窑-部门');
        return true;
    }

    public function updateInstitution(InstitutionFormat $institutionFormat)
    {
        if (empty($institutionFormat->getId())) {
            throw new ApiException('缺少参数', 1);
        }
        $institution = Institution::query()->find($institutionFormat->getId());
        $data = $institutionFormat->toArrayNotNull();
        unset($data['id']);
        $institution->update($data);
        adminLog($institution, AdminActionTypeEnum::UPDATE, '修改清风东窑-部门');
        return true;
    }

    public function deleteInstitution(int $id)
    {
        Institution::query()->find($id)->delete();
        $model = new Institution();
        adminLog($model, AdminActionTypeEnum::DELETE, '删除清风东窑-部门');
        return true;
    }

    public function createLeader(LeaderProfileFormat $leaderProfileFormat)
    {
        adminLog(new LeaderProfile(), AdminActionTypeEnum::CREATE, '创建领导');
        LeaderProfile::query()->create($leaderProfileFormat->toArrayNotNull());
        return true;
    }

    public function createInstitution(InstitutionFormat $institutionFormat)
    {
        adminLog(new Institution(), AdminActionTypeEnum::CREATE, '创建部门');
        Institution::query()->create($institutionFormat->toArrayNotNull());
        return true;
    }

    public function createQingfengProposals(QingfengProposalFormat $qingfengProposalsFormat)
    {
        /** @var null|UserProfile $userProfile */
        $userProfile = UserProfile::query()
            ->select('check_status')
            ->where('user_id', $qingfengProposalsFormat->getUserId())->first();
        if (empty($userProfile)) {
            throw new ApiException('用户不存在', 1);
        }
        if ($userProfile->check_status != CheckStatusEnum::CHECK_ADOPT) {
            throw new ApiException('用户信息未审核', 1);
        }
        if (! $qingfengProposalsFormat->getImages()) {
            $qingfengProposalsFormat->setImages(' ');
        }
        $qingfengProposalsFormat->setCheckStatus(CheckStatusEnum::CHECK_ING);
        $qingfengProposalsFormat->setPushTime(time());
        QingfengProposal::query()->create($qingfengProposalsFormat->toArrayNotNull());
    }

    public function getMyQingfengProposals(int $userId, int $page, int $pageSize, string $orderType)
    {
        $builder = QingfengProposal::query()->where('user_id', $userId);

        $count = $builder->count();

        $list = $builder
            ->orderBy('push_time', $orderType)
            ->skip(($page - 1) * $pageSize)->take($pageSize)->get();

        return [
            'page' => $page,
            'page_size' => $pageSize,
            'count' => $count,
            'list' => $list,
        ];
    }

    public function getMyQingfengProposalDetail(int $userId, int $id)
    {
        return QingfengProposal::query()->where('user_id', $userId)->where('id', $id)
            ->first();
    }

    public function getAllQingfengProposals(int $page, int $pageSize, array $search)
    {
        $builder = QingfengProposal::query();
        if (isset($search['accuse_name'])) {
            $builder->where('accuse_name', 'like', '%' . $search['accuse_name'] . '%');
        }

        if (isset($search['start_date'], $search['end_date'])) {
            $builder->where('push_time', '>=', strtotime($search['start_date']));
            if (strlen($search['end_date']) > 10) {
                $builder->where('push_time', '<=', strtotime($search['end_date']));
            } else {
                $builder->where('push_time', '<=', strtotime($search['end_date']) + (24 * 3600));
            }
        }
        if (isset($search['start_date']) && ! isset($search['end_date'])) {
            $builder->where('push_time', '>=', strtotime($search['start_date']));
        }
        if (! isset($search['start_date']) && isset($search['end_date'])) {
            if (strlen($search['end_date']) > 10) {
                $builder->where('push_time', '<=', strtotime($search['end_date']));
            } else {
                $builder->where('push_time', '<=', strtotime($search['end_date']) + (24 * 3600));
            }
        }

        $count = $builder->count();

        $list = $builder->skip(($page - 1) * $pageSize)->take($pageSize)->get();

        return [
            'page' => $page,
            'pageSize' => $pageSize,
            'count' => $count,
            'list' => $list,
        ];
    }

    public function getAdminQingfengProposalDetail(int $id)
    {
        return QingfengProposal::query()->with('user')->where('id', $id)->first();
    }

    public function deleteQingfengProposal(int $id)
    {
        $proposal = QingfengProposal::query()->find($id);
        if (empty($proposal)) {
            throw new ApiException('数据不存在', 1);
        }
        $proposal->delete();
        return true;
    }
}
